package com.ruoyi.gift.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.gift.domain.MaintenanceRecord;
import com.ruoyi.gift.domain.RoadSign;
import com.ruoyi.gift.domain.dto.MaintenanceRecordQuery;
import com.ruoyi.gift.domain.page.PageResult;
import com.ruoyi.gift.mapper.MaintenanceRecordMapper;
import com.ruoyi.gift.mapper.RoadSignMapper;
import com.ruoyi.gift.service.MaintenanceRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;


@Slf4j
@Service
@RequiredArgsConstructor
public class MaintenanceRecordServiceImpl implements MaintenanceRecordService {

    private final MaintenanceRecordMapper maintenanceRecordMapper;
    private final RoadSignMapper roadSignMapper;

    @Value("${ruoyi.profile}")
    private String profile;

    @Override
    @Transactional
    public void addMaintenanceRecord(MaintenanceRecord maintenanceRecord) {
        // 验证路牌是否存在
        RoadSign roadSign = roadSignMapper.selectBySignCode(maintenanceRecord.getSignCode());
        if (roadSign == null) {
            throw new RuntimeException("路牌不存在，编号：" + maintenanceRecord.getSignCode());
        }

        // 设置路牌ID
        maintenanceRecord.setSignId(roadSign.getId());

        // 计算总费用
        if (maintenanceRecord.getTotalFee() == null) {
            double totalFee = (maintenanceRecord.getServiceFee() != null ? maintenanceRecord.getServiceFee().doubleValue() : 0)
                    + (maintenanceRecord.getPartsFee() != null ? maintenanceRecord.getPartsFee().doubleValue() : 0);
            maintenanceRecord.setTotalFee(java.math.BigDecimal.valueOf(totalFee));
        }
        String username = SecurityUtils.getUsername();
        maintenanceRecord.setCreator(username);

        int result = maintenanceRecordMapper.insert(maintenanceRecord);
        if (result <= 0) {
            throw new RuntimeException("新增维修记录失败");
        }
        log.info("新增维修记录成功，路牌编号：{}", maintenanceRecord.getSignCode());
    }

    @Override
    @Transactional
    public void updateMaintenanceRecord(MaintenanceRecord maintenanceRecord) {
        MaintenanceRecord existing = maintenanceRecordMapper.selectById(maintenanceRecord.getId());
        if (existing == null) {
            throw new RuntimeException("维修记录不存在");
        }

        int result = maintenanceRecordMapper.update(maintenanceRecord);
        if (result <= 0) {
            throw new RuntimeException("更新维修记录失败");
        }
        log.info("更新维修记录成功，ID：{}", maintenanceRecord.getId());
    }

    @Override
    public MaintenanceRecord getById(Long id) {
        return maintenanceRecordMapper.selectById(id);
    }

    @Override
    public List<MaintenanceRecord> getMaintenanceRecordList(MaintenanceRecordQuery query) {
        List<MaintenanceRecord> records = maintenanceRecordMapper.selectList(query);
        return records;
    }

    @Override
    @Transactional
    public void deleteMaintenanceRecord(Long id) {
        MaintenanceRecord existing = maintenanceRecordMapper.selectById(id);
        if (existing == null) {
            throw new RuntimeException("维修记录不存在");
        }

        // 删除维修记录的图片
        deletePhotos(existing.getBeforePhoto());
        deletePhotos(existing.getAfterPhoto());

        int result = maintenanceRecordMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除维修记录失败");
        }
        log.info("删除维修记录成功，ID：{}", id);
    }

    private void deletePhotos(String photoPathsStr) {
        if (photoPathsStr == null || photoPathsStr.trim().isEmpty()) {
            return;
        }

        String[] paths = photoPathsStr.split(",");
        for (String path : paths) {
            path = path.trim();
            if (path.isEmpty()) continue;

            // 提取 /profile 后面的部分
            String relativePath = extractPathAfterProfile(path);
            if (relativePath == null) {
                log.warn("路径不包含 /profile，无法处理: {}", path);
                continue;
            }

            // 构造本地文件路径：D:/ruoyi/uploadPath + /upload/2025/...
            Path file = Paths.get(profile, relativePath);

            try {
                if (Files.exists(file)) {
                    Files.delete(file);
                    log.info("删除文件成功: {}", file.toAbsolutePath());
                } else {
                    log.warn("文件不存在，跳过删除: {}", file.toAbsolutePath());
                }
            } catch (IOException e) {
                log.error("删除文件失败: {}", file.toAbsolutePath(), e);
            }
        }
    }

    /**
     * 从 URL 中提取 /profile 后面的路径部分
     * 例如：http://localhost:8080/profile/upload/... → /upload/...
     *      /profile/upload/... → /upload/...
     */
    private String extractPathAfterProfile(String fullPath) {
        int index = fullPath.indexOf("/profile");
        if (index == -1) {
            return null; // 未找到 /profile
        }
        // 返回 /profile 之后的部分（包含 /upload/...）
        return fullPath.substring(index + "/profile".length());
    }

    @Override
    public List<MaintenanceRecord> getBySignId(Long signId) {
        return maintenanceRecordMapper.selectBySignId(signId);
    }

    @Override
    public List<MaintenanceRecord> getBySignCode(String signCode) {
        return maintenanceRecordMapper.selectBySignCode(signCode);
    }
}
